#include "MessageLabel.h"

MessageLabel::MessageLabel(std::string message, Widget* parent, int x, int y,
		Listener* listener) :
	Widget(x, y, parent) {

	this->message = message;
	this->listener = listener;

	this->active = false;
	this->yes = false;

	this->onSurface = Widget::loadSurface("./trunk/res/img/error_on.png");
	this->offSurface = Widget::loadSurface("./trunk/res/img/error_off.png");

	this->parcel = getPosition();
	parcel.height = this->onSurface->h;
	parcel.width = this->onSurface->w;

	this->activeSurface = this->offSurface;

	SDL_Color textColor = { 0, 0, 0 };
	TTF_Font *font = NULL;
	font = TTF_OpenFont("./trunk/res/font/Neuton.ttf", 18);

	if (font == NULL) {
		Logger::log("MessageLabel", "constructor", "No se cargó la fuente");
	}

	if (this->message != "") {
		char* c_message = new char[this->message.size() + 1];
		strcpy(c_message, this->message.c_str());
		SDL_Surface* textSurface = TTF_RenderText_Solid(font, c_message,
				textColor);
		delete[] c_message;

		SDL_Rect rect;

		rect.x = 0;
		rect.y = (this->parcel.height) / 2;
		rect.w = textSurface->w;
		rect.h = textSurface->h;
		SDL_BlitSurface(textSurface, NULL, this->onSurface, &rect);

	}
}

MessageLabel::~MessageLabel() {
	this->activeSurface = NULL;
	delete this->onSurface;
	delete this->offSurface;
}

void MessageLabel::handleEvent(Event event) {
	if (this->active) {

		Uint16 x = event.getXCoordinate();
		Uint16 y = event.getYCoordinate();

		SDL_Rect rectYes;
		rectYes.x = this->parcel.posX + 475;
		rectYes.y = this->parcel.posY + 2;
		rectYes.w = 55;
		rectYes.h = 21;

		SDL_Rect rectNo;
		rectNo.x = this->parcel.posX + 475;
		rectNo.y = this->parcel.posY + 34;
		rectNo.w = 55;
		rectNo.h = 21;

		if (event.getType() == MouseButtonPressed) {
			if ((x > rectYes.x) && (x < rectYes.x + rectYes.w) && (y
					> rectYes.y) && (y < rectYes.y + rectYes.h)) {
				this->yes = true;
				this->active = false;
			} else if ((x > rectNo.x) && (x < rectNo.x + rectNo.w) && (y
					> rectNo.y) && (y < rectNo.y + rectNo.h)) {
				this->yes = false;
				this->active = false;
			}
		}
	}
}

void MessageLabel::resolve() {
	if (!this->active) {
		this->activeSurface = this->offSurface;
		if (this->yes) {
			this->listener->execute();
			this->yes = false;
		}
	} else {
		this->activeSurface = this->onSurface;
	}
}

void MessageLabel::showOn(SDL_Surface* surface) {
	SDL_Rect rect;
	rect.x = parcel.posX;
	rect.y = parcel.posY;
	rect.w = parcel.width;
	rect.h = parcel.height;

	SDL_BlitSurface(this->activeSurface, NULL, surface, &rect);
}

void MessageLabel::setActive() {
	this->active = true;
}

bool MessageLabel::getYes() {
	return this->yes;
}

bool MessageLabel::isActive() {
	return this->active;
}
